import urllib
import logging
import os
import sys
import copy
from graphy.backends import google_chart_api
from graphy import common
from graphy import line_chart
from MyModel import ManageRegions
from MyModel import ManageNation

class WeeklyGraphController():
  dbRegionManager = ManageRegions()
  dbNationManager = ManageNation()
  def Run(self):
    self.MakeWeeklyGraph()
  
  def MakeWeeklyGraph(self):
     lstUpdateValues = []
     test = None
     lstNationalWeeklyValues = []
     lstNationalWeeklyTotals = [0,0,0,0,0,0,0]
     lstFlattenedNationalValues = [ [0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0] ]
     for lstItemOfTV in  self.dbRegionManager.ReturnPropertyOfRegions("tupleValues"):
        
        if lstItemOfTV[1]:#if the county has values
          lstWeeklyLsts = [ [],[],[],[]  ]#list of lists, each sublist will hold a week's data for each search term
          for stringVal in lstItemOfTV[1]:#List of tuples encoded as strings. Each item is a day's data.Loop executes 7 times.
            test = stringVal
            logging.info(test)
            
           #split to extract the 4 2-tuples(term,value) in it. 
            for i,splitItem in enumerate(stringVal.rsplit("_")):
             #Outer loop runs 7 times (once for each day of the week). Each time the four tuples are looked at and their value put into one of 4 appopriate
             #sublists. Gives structure of eg. [ [0,0,0,8,0,0,0],[0,0,0,6,0,0,0],[0,0,0,12,0,0,0],[0,0,0,1,0,0,0] ]. Each sublist is a different search term and the 7 values
             #in each are the number of mentions on that day
              tupleResult = tuple(eval(splitItem))#convert to tuple
              lstWeeklyLsts[i].append(int(tupleResult[1]))
          x = lstWeeklyLsts
          logging.info(id(lstWeeklyLsts[0]))
          lstNationalWeeklyValues.append(copy.deepcopy(lstWeeklyLsts))
              
          #logging.info(lstWeeklyLsts)  
          lstNumOfTweetsWeekly = [0,0,0,0,0,0,0]#list to hold the total number of tweets for each day in the week
          for lstItem in lstWeeklyLsts:
            for i,subLstItem in enumerate(lstItem):
              lstNumOfTweetsWeekly[i]  = lstNumOfTweetsWeekly[i] + subLstItem#each element in lstNumTweetsWeekly is equal to the sum of values
              
          for listItem in lstWeeklyLsts:#the data for each item each day is then divided by the total data for each day, and the percentage is stored
            for i in range(len(listItem)):
              if lstNumOfTweetsWeekly[i] > 0:
               
                listItem[i] = (float( listItem[i]) / float(lstNumOfTweetsWeekly[i])) * 100/1
                logging.info(lstNumOfTweetsWeekly[i])
               
                
          weeklyChart= google_chart_api.LineChart()
          for lstItemForGraph in lstWeeklyLsts:
            weeklyChart.AddLine(lstItemForGraph, width=line_chart.LineStyle.THICK)
          
          weeklyChart.left.min = 0
          weeklyChart.left.max = 100
          weeklyChart.left.labels = [0, 20, 40, 60,80,100]
          weeklyChart.left.label_positions = [0, 20, 40, 60,80,100]
          totalAxis =  weeklyChart.AddAxis(common.AxisPosition.TOP, common.Axis())
          totalAxis.min = 1
          totalAxis.max = 8
          totalAxis.labels =  ["Mon","Tues","Wed","Thurs","Fri","Sat","Sun"]
        
        
          lstUpdateValues.append([lstItemOfTV[0],("weeklyChart",weeklyChart.display.Img(310, 150))])
     
     
     #A structure containing all of the counties' data( each row has four lists with 7 ints each) for the week was built in the previous step.
     #The following block sums that structure to give a single row list( 4 lists inside it hold the total for each search term for each day.
     for item in lstNationalWeeklyValues:
       for listNo,subItem in enumerate(item):
         for i,value in enumerate(subItem):
           lstFlattenedNationalValues[listNo][i] += value
     logging.info(lstFlattenedNationalValues)
     
     #Now all of the results, regardless of search term, for a day are summed.
     for itemlFNV in  lstFlattenedNationalValues:
        for i in range (0,len(itemlFNV)):
          lstNationalWeeklyTotals[i] += itemlFNV[i]
     
     #Each search term's daily total is then divided by the total results that day and made a percentage.
     for itemlFNV in  lstFlattenedNationalValues:
        for i in range (0,len(itemlFNV)):
          if lstNationalWeeklyTotals[i] > 0:
            itemlFNV[i] = ( float(itemlFNV[i]) / float(lstNationalWeeklyTotals[i]) ) * 100/1
     
     weeklyChart= google_chart_api.LineChart()
     for lstNtItemForGraph in lstFlattenedNationalValues:
       logging.info(lstNtItemForGraph)
       weeklyChart.AddLine(lstNtItemForGraph, width=line_chart.LineStyle.THICK)
        
     weeklyChart.left.min = 0
     weeklyChart.left.max = 100
     weeklyChart.left.labels = [0, 20, 40, 60,80,100]
     weeklyChart.left.label_positions = [0, 20, 40, 60,80,100]
     totalAxis =  weeklyChart.AddAxis(common.AxisPosition.TOP, common.Axis())
     totalAxis.min = 1
     totalAxis.max = 8
     totalAxis.labels =  ["Mon","Tues","Wed","Thurs","Fri","Sat","Sun"]
         
     logging.info(lstNationalWeeklyTotals)   
    
     self.dbNationManager.UpdateNation([ ("weeklyChart",weeklyChart.display.Img(310, 150) )])
     self.dbRegionManager.UpdateRegions(lstUpdateValues)
